package cn.edu.scau.cmi.chenruilin.adapter;

import java.util.ArrayList;
import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.cell.PropertyValueFactory;

public class ClassAdapterController {
	@FXML
    private TableView result;

    @FXML
    private TextField input_name;

    @FXML
    private TextField input_id;
    
    @FXML
    private TableColumn Id;

    @FXML
    private TableColumn Name;
    @FXML
    private Button addition;
    
    private static List<Student> student;

    @FXML
    public void add() {
    	try{
    		
    		int flag = 0;
        	int stuID = Integer.parseInt(input_id.getText());
        	for(int i=0;i<student.size();i++) {
    			if(student.get(i).getId()==stuID) {
    				Alert al = new Alert(AlertType.WARNING);
    	    		al.setTitle("WARNING");
    	    		al.setHeaderText(null);
    	    		al.setContentText("该学号已有！");
    	    		al.showAndWait();
    	    		flag = 1;
    			}
    		}
        	if(flag == 0) {
        		String stuName = input_name.getText();
            	Student s = new Student();
            	s.setId(stuID);
            	s.setName(stuName);
            	student.add(s);
            	AdapterOfClass adapter = new AdapterOfClass();
            	student = adapter.sort(student);
            	ObservableList<Student> stu = FXCollections.observableArrayList();
        		for(int i=0;i<student.size();i++) {
        			stu.add(student.get(i));
        		}
        		Id.setCellValueFactory(new PropertyValueFactory<Student,Integer>("id"));
        		Name.setCellValueFactory(new PropertyValueFactory<Student,String>("name"));
        		result.setItems(stu);
        	}
    	}
    	catch(Exception e) {
    		Alert al = new Alert(AlertType.WARNING);
    		al.setTitle("WARNING");
    		al.setHeaderText(null);
    		al.setContentText("请确保学号和姓名都已输入！");
    		al.showAndWait();
    	}
    	
    }
    
    @FXML
    public void initialize() {
    	student = new ArrayList();
    }
}
